package com.hbzhit.modules.cm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbzhit.common.utils.PageUtils;
import com.hbzhit.common.utils.Query;
import com.hbzhit.modules.cm.dao.ContentDao;
import com.hbzhit.modules.cm.entity.ContentEntity;
import com.hbzhit.modules.cm.form.ContentListQueryForm;
import com.hbzhit.modules.cm.form.ContentPageQueryForm;
import com.hbzhit.modules.cm.service.ContentService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * 内容发布
 *
 * @author hbzhit
 **/
@Service("contentService")
public class ContentServiceImpl extends ServiceImpl<ContentDao, ContentEntity> implements ContentService {

    @Override
    public PageUtils<ContentEntity> queryPage(ContentPageQueryForm params) {
        IPage<ContentEntity> page = this.page(
                new Query<ContentEntity>().getPage(params),
                new LambdaQueryWrapper<ContentEntity>()
                        .eq(StrUtil.isNotEmpty(params.getNodeFlag()), ContentEntity::getNodeFlag, params.getNodeFlag())
                        .and(StrUtil.isNotEmpty(params.getKey()), wrapper -> wrapper
                                .like(ContentEntity::getTitle, params.getKey())
                                .or()
                                .like(ContentEntity::getSummary, params.getKey())
                        )
                        .eq(ObjectUtil.isNotEmpty(params.getStatus()), ContentEntity::getStatus, params.getStatus())
                        .orderByAsc(ContentEntity::getOrderNum)
                        .orderByDesc(ContentEntity::getCreateTime)
                        .select(ContentEntity.class, i -> ObjectUtil.notEqual(i.getColumn(), "content"))
        );
        return new PageUtils<>(page);
    }

    @Override
    public List<ContentEntity> queryList(ContentListQueryForm params) {
        return this.list(new LambdaQueryWrapper<ContentEntity>()
                .select(ContentEntity.class, i -> ObjectUtil.notEqual(i.getColumn(), "content"))
        );
    }

    @Override
    public ContentEntity getById(Serializable id) {
        ContentEntity entity = super.getById(id);

        //浏览量 +1
        entity.setReadNum((entity.getReadNum() == null ? 0 : entity.getReadNum()) + 1);
        this.updateById(entity);

        return entity;
    }
}
